package dhm.com.dhmshop.framework.module.commodity.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.home.ImageDetailAdapter;
import dhm.com.dhmshop.adapter.order.ParamTypeAdapter;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.Bean;
import dhm.com.dhmshop.entity.GetCollectionList;
import dhm.com.dhmshop.entity.GetCollectionShop;
import dhm.com.dhmshop.entity.GetGoodsFreightBean;
import dhm.com.dhmshop.entity.GetGoodsSpecsBean;
import dhm.com.dhmshop.entity.Orderdetail;
import dhm.com.dhmshop.entity.ShopCarBean;
import dhm.com.dhmshop.framework.base.BaseActivity;
import dhm.com.dhmshop.framework.module.commodity.base.GradationScrollView;
import dhm.com.dhmshop.framework.module.commodity.base.NoScrollListView;
import dhm.com.dhmshop.framework.module.commodity.base.ScrollViewContainer;
import dhm.com.dhmshop.framework.module.commodity.base.StatusBarUtil;
import dhm.com.dhmshop.framework.module.commodity.entity.OneGoodsEntity;
import dhm.com.dhmshop.framework.module.commodity.model.CommodityDetailsModel;
import dhm.com.dhmshop.framework.module.commodity.view.CommodityDetailsView;
import dhm.com.dhmshop.framework.module.home.activity.SearchActivity;
import dhm.com.dhmshop.framework.module.home.entity.HotBannerEntity;
import dhm.com.dhmshop.framework.utils.GlideUtil;
import dhm.com.dhmshop.framework.utils.StringUtil;
import dhm.com.dhmshop.updata.activity.GoodsconsultActivity;
import dhm.com.dhmshop.updata.activity.ShopdetailActivity;
import dhm.com.dhmshop.utils.CustomJiaJian;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.view.home.GoodspingActivity;
import dhm.com.dhmshop.view.home.OrderdetailActivity;


public class CommodityDetailsActivity extends BaseActivity<CommodityDetailsModel> implements CommodityDetailsView, LoginContract.IView, View.OnClickListener, GradationScrollView.ScrollViewListener {

    private int uid;
    private int gid;
    private int shop_id;
    private List<OneGoodsEntity> commodityDetailstitles;
    private ImageView commdetaiImg;
    private TextView intoShop;
    private TextView oldPrice;
    private PressenterImpl pressenter;
    private Banner home_banner;
    /**
     * 188
     */
    private TextView commdePrice;
    private TextView yunfei;
    private TextView xiaoliang;
    private TextView area;
    private RelativeLayout commde_ask;
    private RelativeLayout param;
    private ImageView shopImage;
    private TextView shop_name;
    private TextView shop_type;
    private TextView goodscount;
    private TextView timecount;
    private TextView servicecount;
    private TextView alldoods;
    private TextView content;
    /**
     * WOODWICK无烟精油香氛大豆蜡烛 亚麻240G国内发货（预计1-3工作日内送达）
     */
    private TextView commdeTitle;
    private ImageView collection;
    /**
     * (1111)
     */
    private RelativeLayout commdeComment;
    /**
     * 继续拖动,查看图文详情
     */
//    private GradationScrollView scrollview;
    private NoScrollListView commdetialNoscllv;
    /**
     * 已经最到底啦!
     */
    private ImageView commdeFanhui;
    private ImageView commdeShare;
    private LinearLayout commdeService;
    private LinearLayout commdeCollected;
    private LinearLayout commdeShop;
    private RecyclerView recy_image;
    /**
     * 加入购物车
     */
    private TextView commdetailJiaru;
    /**
     * 立即购买
     */
    private TextView commdetailBuy;
    private LinearLayout commdetailBottom;
    private LinearLayout commdeTitleLl;
    private ScrollViewContainer container;

    private ScrollView svContainer;
    private LinearLayout image;

    private int height;
    private int width;
    private OneGoodsEntity oneGoodsEntit;
    private boolean isbuy;
    //    判断当前浏览者是否已经收藏此商品，0否，1是
    private int is_collect;
    //判断当前浏览者是否已经点赞此商品，0否，1是
    private int is_support;
    private ImageDetailAdapter imageDetailAdapter;

    String H5String = "";
    private TextView commde_price;
    private TextView goodsoldprice;
    private SimpleDraweeView goods_image;
    private String specIds;
    private float allprice;
    private GetGoodsFreightBean getGoodsFreightBean;
    private int isbuy1;


    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        //透明状态栏
//        StatusBarUtil.setTranslucentForImageView(this, commdeTitleLl);
        getWindow().setStatusBarColor(Color.WHITE);
        initViews();

      /*  LinearLayout.LayoutParams params1 = (LinearLayout.LayoutParams) commdeTitleLl.getLayoutParams();
        params1.setMargins(15, -StatusBarUtil.getStatusBarHeight(this) / 4, 15, 0);
        commdeTitleLl.setLayoutParams(params1);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) commdetaiImg.getLayoutParams();
        params.height = getScreenHeight(this) * 2 / 3;
        commdetaiImg.setLayoutParams(params);*/

        container = new ScrollViewContainer(getApplicationContext());
        Intent intent = getIntent();
        isbuy1 = 0;
        uid = Integer.parseInt(SpUtils.getString(this, "uid"));

        gid = intent.getIntExtra("gid", 1);
        shop_id = intent.getIntExtra("shop_id", 1);
        commodityDetailstitles = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        imageDetailAdapter = new ImageDetailAdapter(this);

        recy_image.setLayoutManager(manager);
        recy_image.setAdapter(imageDetailAdapter);


    }

    private void initViews() {
        home_banner = findViewById(R.id.home_banner);
        commdetaiImg = findViewById(R.id.commdetai_img);
        collection = findViewById(R.id.collection);
        intoShop = findViewById(R.id.intoShop);
        intoShop.setOnClickListener(this);


        svContainer = (ScrollView) findViewById(R.id.sv_container);
        image = (LinearLayout) findViewById(R.id.image);



        yunfei = findViewById(R.id.yunfei);
        xiaoliang = findViewById(R.id.xiaoliang);
        area = findViewById(R.id.area);
        commde_ask = findViewById(R.id.commde_ask);
        commde_ask.setOnClickListener(this);
        param = findViewById(R.id.param);
        param.setOnClickListener(this);
        shopImage = findViewById(R.id.shopImage);
        shop_name = findViewById(R.id.shop_name);
        shop_type = findViewById(R.id.shop_type);
        goodscount = findViewById(R.id.goodscount);
        timecount = findViewById(R.id.timecount);
        servicecount = findViewById(R.id.servicecount);
        alldoods = findViewById(R.id.alldoods);
        alldoods.setOnClickListener(this);
        content = findViewById(R.id.content);


        commdePrice = findViewById(R.id.commde_price);
        commdeTitle = findViewById(R.id.commde_title);
        commdeComment = findViewById(R.id.commde_comment);
        commdeComment.setOnClickListener(this);
//        scrollview = findViewById(R.id.scrollview);
        oldPrice = findViewById(R.id.old_price);
        commdetialNoscllv = findViewById(R.id.commdetial_noscllv);
        recy_image = findViewById(R.id.recy_image);
        commdeFanhui = findViewById(R.id.commde_fanhui);
        commdeFanhui.setOnClickListener(this);
        commdeShare = findViewById(R.id.commde_share);
        commdeService = findViewById(R.id.commde_service);
        commdeService.setOnClickListener(this);
        commdeCollected = findViewById(R.id.commde_collected);
        commdeCollected.setOnClickListener(this);
        commdeShop = findViewById(R.id.commde_shop);
        commdeShop.setOnClickListener(this);
        commdetailJiaru = findViewById(R.id.commdetail_jiaru);
        commdetailJiaru.setOnClickListener(this);
        commdetailBuy = findViewById(R.id.commdetail_buy);
        commdetailBuy.setOnClickListener(this);
        commdetailBottom = findViewById(R.id.commdetail_bottom);
        commdeTitleLl = findViewById(R.id.commde_titlell);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

    }

    @Override
    protected void initData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("goodsId", gid + "");
        map.put("uid", uid + "");
        pressenter.sendMessage(CommodityDetailsActivity.this, Constant.OneGoods, map, OneGoodsEntity.class);
    }

    @Override
    protected void initListener() {
        ViewTreeObserver vto = commdetaiImg.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                commdeTitleLl.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                height = commdetaiImg.getHeight();

//                scrollview.setScrollViewListener(CommodityDetailsActivity.this);
            }
        });
    }

    @Override
    protected int intiLayoutId() {
        return R.layout.activity_commodity_details;
    }

    @Override
    protected CommodityDetailsModel initModel() {
        return new CommodityDetailsModel();
    }

    @Override
    public void getCommodityDetails(OneGoodsEntity oneGoodsEntity) {
//        if (oneGoodsEntity != null || oneGoodsEntity.getData().getComment().size() > 0) {
//            oneGoodsEntit = oneGoodsEntity;
//            String image = oneGoodsEntity.getData().getGoods_images().get(0);
//            OneGoodsEntity.DataBean.ShopInfoBean shop_info = oneGoodsEntity.getData().getShop_info();
//            GlideUtil.loadImage(CommodityDetailsActivity.this, StringUtil.preventNull(image), commdetaiImg);
//            commdePrice.setText(StringUtil.preventNull(oneGoodsEntity.getData().getPrice()));
//            commdeTitle.setText(StringUtil.preventNull(oneGoodsEntity.getData().getGoods_name()));
//            commedLocationtv.setText(StringUtil.preventNull(shop_info.getProvince() + shop_info.getCity()));
//            commoDityDetailsShopTv.setText(StringUtil.preventNull(shop_info.getStore_name()));
//            is_collect = oneGoodsEntit.getData().getIs_collect();
//            is_support = oneGoodsEntit.getData().getIs_support();
//            if (is_collect == 0) {
//                collection.setImageResource(R.mipmap.commodditydetails_notcollected);
//            } else {
//                collection.setImageResource(R.mipmap.commodditydetails_collected);
//            }
//            imageDetailAdapter.setShopList(oneGoodsEntity.getData().getGoods_content_images());
//        }
    }

    private static final int MY_PERMISSIONS_CALL_PHONE = 1;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.commde_fanhui:
                finish();
                break;
            case R.id.commde_ask:
                intent=new Intent(CommodityDetailsActivity.this, GoodsconsultActivity.class);
                intent.putExtra("goodsId",oneGoodsEntit.getData().getGoodsId());
                startActivity(intent);
                break;
            case R.id.param:

                break;
            case R.id.alldoods:
                intent=new Intent(CommodityDetailsActivity.this, SearchActivity.class);
                intent.putExtra("shop_id",shop_id+"");
                intent.putExtra("type","1");
                startActivity(intent);
                break;
            case R.id.commde_comment:
                intent = new Intent(CommodityDetailsActivity.this, GoodspingActivity.class);
                intent.putExtra("gid", gid);
                startActivity(intent);
                break;
            case R.id.commde_service:

                ClipboardManager systemService = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                if (oneGoodsEntit!=null){
                    String shopQQ = oneGoodsEntit.getData().getShop().getShopQQ();
                    systemService.setText(shopQQ);
                    Toast.makeText(this, "已复制联系QQ", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "QQ 为空，复制失败", Toast.LENGTH_SHORT).show();

                }


                /**
                 * 高版本手机动态获取打电话权限
                 */
/*
                if (Build.VERSION.SDK_INT >= 23) {
                    ActivityCompat.requestPermissions(CommodityDetailsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_CALL_PHONE);

                    Intent intent2 = new Intent();
                    intent2.setAction(Intent.ACTION_CALL);
//                    intent2.setData(Uri.parse("tel:" + oneGoodsEntit.getData().getShop_info().getMobile()));
                    startActivity(intent2);
                }
*/

                break;
            case R.id.commde_collected:
                if (is_collect == 0) {
//                    收藏
                    Map<String, String> map = new HashMap();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid + "");
                    map.put("type", "0");
                    map.put("id", gid + "");
                    pressenter.sendMessage(CommodityDetailsActivity.this, Constant.CollectionGoods, map, Bean.class);
                } else {
//                    取消收藏
                    Map<String, String> map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid + "");
                    pressenter.sendMessage(CommodityDetailsActivity.this, Constant.CollectionList, map, GetCollectionList.class);
                }
                break;
            case R.id.commde_shop:
                if(oneGoodsEntit.getData()!=null){
                    intent = new Intent(CommodityDetailsActivity.this, ShopdetailActivity.class);
                    intent.putExtra("shop_id", oneGoodsEntit.getData().getShopId() + "");
                    startActivity(intent);
                }else {
                    Toast.makeText(CommodityDetailsActivity.this,"请检查网络",Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.commdetail_jiaru:
                isbuy = false;
                setBackgroundAlpha(0.5f);
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.commdetail_buy:
                isbuy = true;
                if (popWindow!=null){
                setBackgroundAlpha(0.5f);
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            }else {
                    showPopwindow();
                }
                break;
            case R.id.intoShop:

                intent = new Intent(CommodityDetailsActivity.this, ShopdetailActivity.class);
                intent.putExtra("shop_id", oneGoodsEntit.getData().getShopId() + "");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {   //设置标题的背景颜色
            commdeTitleLl.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
        } else if (y > 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / height;
            float alpha = (255 * scale);
            commdeTitleLl.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
        } else {    //滑动到banner下面设置普通颜色
            commdeTitleLl.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
        }
    }

    private PopupWindow popWindow;
    private int num = 1;

    float nowPrice = 0;

    private void showPopwindow() {
        View popView = View.inflate(this, R.layout.popup_param, null);
        ImageView cancle = popView.findViewById(R.id.cancle);
        TextView kucun = popView.findViewById(R.id.kucun);
        goods_image = popView.findViewById(R.id.image);
        commde_price = popView.findViewById(R.id.commde_price);
        goodsoldprice = popView.findViewById(R.id.param);
        goodsoldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        kucun.setText("库存："+oneGoodsEntit.getData().getGoodsStock()+oneGoodsEntit.getData().getGoodsUnit());
        RecyclerView recy = popView.findViewById(R.id.recy);
        Button sure = popView.findViewById(R.id.sure);
        CustomJiaJian jiajian = popView.findViewById(R.id.jiajian);
        jiajian.setCustomListener(new CustomJiaJian.CustomListener() {
            @Override
            public void jiajian(int count) {
                num = count;
//                commde_price.setText(count * Float.parseFloat(oneGoodsEntit.getData().getExpress_price()) + "");
            }

            @Override
            public void shuRuZhi(int count) {
                num = count;
//                commde_price.setText(count * Float.parseFloat(oneGoodsEntit.getData().getExpress_price()) + "");
            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isbuy) {
                    isbuy1 = 0;
                    Map<String, String> map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("goods_id", oneGoodsEntit.getData().getGoodsId() + "");
                    map.put("buyNum", num + "");
                    map.put("uid", uid + "");
                    map.put("goodsSpecId", goodsSpecId);
                    pressenter.sendMessage(CommodityDetailsActivity.this, Constant.AddShopping, map, Bean.class);
                } else {
                    isbuy1 = 1;
                    Map<String, String> map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("goods_id", oneGoodsEntit.getData().getGoodsId() + "");
                    map.put("uid", uid + "");
                    pressenter.sendMessage(CommodityDetailsActivity.this, Constant.DefGoodsShopping, map, Bean.class);
                }
            }
        });
        nowPrice = Float.parseFloat(oneGoodsEntit.getData().getShopPrice());
        commde_price.setText(oneGoodsEntit.getData().getShopPrice());
        allprice = Float.parseFloat(oneGoodsEntit.getData().getShopPrice())*num;
        goods_image.setImageURI(Constant.PATH + "/" + oneGoodsEntit.getData().getGoodsImg());
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        ParamTypeAdapter paramTypeAdapter = new ParamTypeAdapter(this);
        paramTypeAdapter.setaddClick(new ParamTypeAdapter.OnIntentClick() {
            @Override
            public void item(int posttion, int childposttion) {
                for (int j = 0; j < oneGoodsEntit.getData().getSpec().get(posttion).getList().size(); j++) {
                    oneGoodsEntit.getData().getSpec().get(posttion).getList().get(j).setParam_check("0");
                }
                oneGoodsEntit.getData().getSpec().get(posttion).getList().get(childposttion).setParam_check("1");
                if (!oneGoodsEntit.getData().getSpec().get(posttion).getList().get(childposttion).getItemImg().equals("")) {
                    goods_image.setImageURI(Constant.PATH + "/" + oneGoodsEntit.getData().getSpec().get(posttion).getList().get(childposttion).getItemImg());
                }
                getSpecIds();
                paramTypeAdapter.setImageList(oneGoodsEntit.getData().getSpec());
            }
        });

        recy.setAdapter(paramTypeAdapter);

        if (oneGoodsEntit.getData().getSpec() == null || oneGoodsEntit.getData().getSpec().size() == 0) {
            recy.setVisibility(View.GONE);
        } else {
            for (int i = 0; i < oneGoodsEntit.getData().getSpec().size(); i++) {
                oneGoodsEntit.getData().getSpec().get(i).getList().get(0).setParam_check("1");
            }
            paramTypeAdapter.setImageList(oneGoodsEntit.getData().getSpec());
        }


        if (oneGoodsEntit.getData().getSpec() != null && oneGoodsEntit.getData().getSpec().size() > 0) {
            getSpecIds();
        }
        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });


    }

    private void getSpecIds() {
        int array[] = new int[oneGoodsEntit.getData().getSpec().size()];
        for (int i = 0; i < oneGoodsEntit.getData().getSpec().size(); i++) {
            for (int j = 0; j < oneGoodsEntit.getData().getSpec().get(i).getList().size(); j++) {
                if (oneGoodsEntit.getData().getSpec().get(i).getList().get(j).getParam_check().equals("1")) {
                    array[i] = Integer.parseInt(oneGoodsEntit.getData().getSpec().get(i).getList().get(j).getItemId());
                }
            }
        }
        specIds = "";

        for (int i = 0; i < array.length; i++) {
            specIds = specIds + array[i] + ":";
        }

        specIds = specIds.substring(0, specIds.length() - 1);

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("goods_id", gid + "");
        map.put("specIds", specIds);

        pressenter.sendMessage(CommodityDetailsActivity.this, Constant.GetGoodsSpecs, map, GetGoodsSpecsBean.class);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof Bean) {
            Bean bean = (Bean) data;
            if (bean.getMessage().equals("足迹保留成功")) {
                return;
            }
            if (isbuy1==1){
                isbuy1 = 0;
                Map<String, String> map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                map.put("goods_id", oneGoodsEntit.getData().getGoodsId() + "");
                map.put("buyNum", num + "");
                map.put("uid", uid + "");
                map.put("goodsSpecId", goodsSpecId);
                pressenter.sendMessage(CommodityDetailsActivity.this, Constant.AddShopping, map, Bean.class);
            }else {
                Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            }

            if (bean.getCode() == 1) {
                if (bean.getMessage().equals("关注成功")) {
                    is_collect = 1;
                    collection.setImageResource(R.mipmap.commodditydetails_collected);
                }else if (bean.getMessage().equals("取消成功")) {
                    is_collect = 0;
                    collection.setImageResource(R.mipmap.commodditydetails_notcollected);
                } else if (bean.getMessage().equals("添加成功")) {
                    popWindow.dismiss();
                    if (isbuy) {
//                        去下单
                        List<ShopCarBean> shopCarBeans=new ArrayList<>();
                        ShopCarBean shopCarBean=new ShopCarBean();
                        shopCarBean.setShopName(oneGoodsEntit.getData().getShop().getShopName());
                        shopCarBean.setPeisong("快递运输");
                        ShopCarBean.GoodsBeans goodsBeans=new ShopCarBean.GoodsBeans();
                        goodsBeans.setCount(num+"");
                        goodsBeans.setGoods_id(oneGoodsEntit.getData().getGoodsId());
                        goodsBeans.setGoods_image(oneGoodsEntit.getData().getGoodsImg());
                        goodsBeans.setName(oneGoodsEntit.getData().getGoodsName());
                        goodsBeans.setPrice(oneGoodsEntit.getData().getShopPrice());
                        shopCarBean.addGoodsbean(goodsBeans);
                        shopCarBeans.add(shopCarBean);
                        if (oneGoodsEntit.getData().getIsFreeShipping().equals("1")){
                            shopCarBean.setHeji(allprice+"");
                            shopCarBean.setYunfei("0.00");
                            Intent intent=new Intent(this, OrderdetailActivity.class);
                            intent.putExtra("shopCarBean", (Serializable) shopCarBeans);
                            startActivity(intent);
                        }else {
                            shopCarBean.setHeji((allprice+getGoodsFreightBean.getData())+"");
                            shopCarBean.setYunfei(getGoodsFreightBean.getData()+"");Intent intent=new Intent(this, OrderdetailActivity.class);
                            intent.putExtra("shopCarBean", (Serializable) shopCarBeans);
                            startActivity(intent);
                        }
                    }
                }
            }
        } else if (data instanceof GetCollectionList) {
            GetCollectionList getCollectionShop = (GetCollectionList) data;
            if (getCollectionShop.getCode() == 1) {
                for (int i = 0; i < getCollectionShop.getData().size(); i++) {
                    if (gid == getCollectionShop.getData().get(i).getGoodsId()) {
                        Map<String, String> map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("uid", uid + "");
                        map.put("type", "0");
                        map.put("cid", getCollectionShop.getData().get(i).getFavoriteId() + "");
                        pressenter.sendMessage(CommodityDetailsActivity.this, Constant.DelCollect, map, Bean.class);
                    } else {
                    }
                }
            }
        } else if (data instanceof OneGoodsEntity) {
            OneGoodsEntity oneGoodsEntity = (OneGoodsEntity) data;
            Log.e("ss::",oneGoodsEntity.getMessage());

            oneGoodsEntit = oneGoodsEntity;
            if (oneGoodsEntit.getCode() == 1) {
                commdeTitle.setText(oneGoodsEntit.getData().getGoodsName());
                commdePrice.setText(oneGoodsEntit.getData().getShopPrice());
                shop_name.setText(oneGoodsEntit.getData().getShop().getShopName());
                shop_type.setText("主营：" + oneGoodsEntit.getData().getShop().getCatshops());
                oldPrice.setText("￥ " + oneGoodsEntit.getData().getMarketPrice());
                xiaoliang.setText(oneGoodsEntit.getData().getSaleNum());
                area.setText(oneGoodsEntit.getData().getShop().getAreas().getAreaName1() + oneGoodsEntit.getData().getShop().getAreas().getAreaName2());
                GlideUtil.loadImage(CommodityDetailsActivity.this, "/" + oneGoodsEntit.getData().getShop().getShopImg(), shopImage);
                is_collect = oneGoodsEntit.getData().getFavGood();
                if (is_collect == 0) {
                    collection.setImageResource(R.mipmap.commodditydetails_notcollected);
                } else {
                    collection.setImageResource(R.mipmap.commodditydetails_collected);
                }
                goodscount.setText(oneGoodsEntit.getData().getShop().getScores().getGoodsScore());
                servicecount.setText(oneGoodsEntit.getData().getShop().getScores().getServiceScore());
                timecount.setText(oneGoodsEntit.getData().getShop().getScores().getTimeScore());

                shop_id=Integer.parseInt(oneGoodsEntit.getData().getShop().getShopId());

                if (oneGoodsEntit.getData().getIsFreeShipping().equals("1")){
                    yunfei.setText("快递:免运费");
                }else {
                    Map<String, String> map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("shop_id", oneGoodsEntit.getData().getShopId());
                    map.put("shippingFeeType", oneGoodsEntit.getData().getShippingFeeType());
                    map.put("goodsNum", num + "");
                    map.put("goodsWeight", oneGoodsEntit.getData().getGoodsWeight());
                    map.put("goodsVolume", oneGoodsEntit.getData().getGoodsVolume());
                    if (oneGoodsEntit.getData().getShopExpressId().equals("0")){
                        map.put("shopExpressId", "1");
                    }else {
                        map.put("shopExpressId", oneGoodsEntit.getData().getShopExpressId());
                    }
                    pressenter.sendMessage(CommodityDetailsActivity.this, Constant.GetGoodsFreight, map, GetGoodsFreightBean.class);
                }
                home_banner.setImages(oneGoodsEntit.getData().getGallery())
                        .setDelayTime(3000)
                        .isAutoPlay(true)
                        .setBannerAnimation(Transformer.DepthPage)
                        .setOnBannerListener((position -> {//banner点击监听

                        }))
                        .setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                GlideUtil.loadImage(context, "/" + path, imageView);
                            }
                        }).start();


                H5String = oneGoodsEntit.getData().getGoodsDesc();
                StringBuffer stringBuffer = new StringBuffer(H5String);
                boolean b = true;
                int j = 0;
                while (b) {
                    j = H5String.indexOf("data-original", j + 4);
                    if (j == -1) {
                        b = false;
                    } else {
                        H5String = stringBuffer.replace(j, j + 13, "src").toString();
                    }
                }
                boolean a = true;
                int i = 0;
                while (a) {
                    if (i == 0) {
                        i = H5String.indexOf("/upload", i);
                    } else {
                        i = H5String.indexOf("/upload", i + 30);
                    }
                    if (i == -1) {
                        a = false;
                    } else {
                        H5String = stringBuffer.insert(i, "http://www.qitong.shop").toString();
                    }
                }
                getAndSetStrToTextView();

                showPopwindow();

                Map<String, String> map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                map.put("uid", uid + "");
                map.put("shop_id", oneGoodsEntit.getData().getShopId() + "");
                map.put("goods_id", gid + "");
                pressenter.sendMessage(CommodityDetailsActivity.this, Constant.FootGoods, map, Bean.class);


            }


//            if (oneGoodsEntity != null || oneGoodsEntity.getData().getComment().size() > 0) {
//                oneGoodsEntit = oneGoodsEntity;
//                String image = oneGoodsEntity.getData().getGoods_images().get(0);
//                OneGoodsEntity.DataBean.ShopInfoBean shop_info = oneGoodsEntity.getData().getShop_info();
//                GlideUtil.loadImage(CommodityDetailsActivity.this, StringUtil.preventNull(image), commdetaiImg);
//                commdePrice.setText(StringUtil.preventNull(oneGoodsEntity.getData().getPrice()));
//                commdeTitle.setText(StringUtil.preventNull(oneGoodsEntity.getData().getGoods_name()));
//                commedLocationtv.setText(StringUtil.preventNull(shop_info.getProvince() + shop_info.getCity()));
//                commoDityDetailsShopTv.setText(StringUtil.preventNull(shop_info.getStore_name()));
//                is_collect = oneGoodsEntit.getData().getIs_collect();
//                is_support = oneGoodsEntit.getData().getIs_support();
//                if (is_collect == 0) {
//                    collection.setImageResource(R.mipmap.commodditydetails_notcollected);
//                } else {
//                    collection.setImageResource(R.mipmap.commodditydetails_collected);
//                }
//                imageDetailAdapter.setShopList(oneGoodsEntity.getData().getGoods_content_images());
//            }

        } else if (data instanceof GetGoodsSpecsBean) {
            GetGoodsSpecsBean getGoodsSpecsBean = (GetGoodsSpecsBean) data;
            allprice = Float.parseFloat(getGoodsSpecsBean.getData().getSpecPrice())*num;
            if (getGoodsSpecsBean.getCode() == 1) {
                commde_price.setText(getGoodsSpecsBean.getData().getSpecPrice());
                goodsoldprice.setText(getGoodsSpecsBean.getData().getMarketPrice());
                goodsSpecId = getGoodsSpecsBean.getData().getId() + "";
            }
        }else if (data instanceof GetGoodsFreightBean){
            getGoodsFreightBean = (GetGoodsFreightBean) data;
            yunfei.setText("快递: ￥"+getGoodsFreightBean.getData());
        }

    }


    String goodsSpecId = "0";


    @Override
    public void fail(String error) {

            commdetailBottom.setVisibility(View.GONE);
            svContainer.setVisibility(View.GONE);
            image.setVisibility(View.VISIBLE);

    }

    /**
     * 获取并设置字符串到TextView
     */
    private void getAndSetStrToTextView() {
        final HashSet<String> keyWordsSet = getAllKeyWords();

        new Thread(new Runnable() {     //之所以放在线程中完成H5转 SpannableStirng ，是为了加载H5的图片
            @Override
            public void run() {
                Spanned normalStr = convertH5TextToSpanned();
                SpannableString spannableStr = new SpannableString(normalStr);  //最终要展示的字符串

                tempSplitedStr = spannableStr.toString();      //全局变量，赋初值

                for (String keyStr : keyWordsSet) { //为所有关键字增加点击事件
                    findKeyAndSetEvent(spannableStr, tempSplitedStr, keyStr, 0);
                }

                Message msg = handler.obtainMessage();
                msg.what = FLAG_CONVERT_H5TEXT_OVER;
                msg.obj = spannableStr;
                handler.sendMessage(msg);
            }
        }).start();
    }


    /**
     * 将H5字符串转换成Spanned字符串保证图片的显示。
     */
    private Spanned convertH5TextToSpanned() {
        return Html.fromHtml(H5String, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String url) {
                InputStream is;
                try {
                    is = (InputStream) new URL(url).getContent();
                    Drawable d = Drawable.createFromStream(is, "src");

                    setDrawableBounds(d, MODE_BASE_WINDOW_WITH);  //设置图片区域

                    is.close();
                    return d;
                } catch (Exception e) {
                    return null;
                }
            }
        }, null);
    }

    /**
     * 设置图片的区域，必须设置，否则图片不展示
     *
     * @param d                图片对象
     * @param withOrHeightMode 宽高模式
     */
    private void setDrawableBounds(Drawable d, int withOrHeightMode) {
        switch (withOrHeightMode) {
            case MODE_INTRINSIC:    //根据原图大小进行展示
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                break;
            case MODE_BASE_WINDOW_WITH: //与屏幕等宽
                WindowManager wm = getWindowManager();
                int wmWidth = wm.getDefaultDisplay().getWidth();
                int picWidth = d.getIntrinsicWidth();
                int picHeight = d.getIntrinsicHeight();

                picHeight = (int) (picHeight * ((wmWidth / picWidth)+1));

                d.setBounds(0, 0, wmWidth, picHeight);
        }
    }

    /**
     * 找出单个关键字每一次出现的位置并为其增加点击事件
     *
     * @param tempSplitedStr 被切割后的新字符串
     * @param keyStr         关键字
     * @param preEndIndex    关键词上一次出现时的结束索引/关键字本次在原始字符串中的结束索引
     */
    private void findKeyAndSetEvent(SpannableString spannableString, String tempSplitedStr, final String keyStr,
                                    int preEndIndex) {
        final int startIndex = tempSplitedStr.indexOf(keyStr);     //起始索引
        if (startIndex != -1) {
            final int endIndex = startIndex + keyStr.length() - 1;    //终止索引,
            int startIndexInOgirinal = 0;
            if (preEndIndex == 0) {    //关键字第一次出现
                startIndexInOgirinal = startIndex;
                preEndIndex = endIndex;
            } else {      //关键字不是第一次出现
                startIndexInOgirinal = startIndex + preEndIndex + 1;    //加1 是因为截取的字符串索引又是从0开始
                preEndIndex = startIndexInOgirinal + keyStr.length() - 1;   //减1 是因为起始索引已经占了一个索引
            }
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //点击事件弹窗+请求服务器数据
                    Toast.makeText(CommodityDetailsActivity.this, "点我干嘛？关键字：" + keyStr, Toast.LENGTH_SHORT).show();
                }
                @Override
                public void updateDrawState(TextPaint ds) {
                    //super.updateDrawState(ds);
                    ds.setColor(Color.RED);      //更改超链接颜色(此颜色要与H5中关键字的 font 颜色一致)
                    ds.setUnderlineText(false);     //不展示下划线
                }
            }, startIndexInOgirinal, preEndIndex + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            //}, startIndexInOgirinal, preEndIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);  //这样的话，非第一次出现的只会将第一个字符加上超链接

            tempSplitedStr = tempSplitedStr.substring(endIndex + 1);  //截取字符串，+1 表示从关键词后面截取，不含关键字；不加1 的话从关键词最后一个字开始截取
            findKeyAndSetEvent(spannableString, tempSplitedStr, keyStr, preEndIndex);     //递归调用
        }
    }

    /**
     * 获取关键字，并使用Set存储，实现去重
     */
    private HashSet<String> getAllKeyWords() {
        HashSet<String> keysSet = new HashSet<>();
        Document document = Jsoup.parse(H5String);
        Elements elementsList = document.getElementsByTag("font"); //在JSOUP中，Elements类继承自ArrayList

        if (null != elementsList) {
            for (Element element : elementsList) {
                keysSet.add(element.text());
            }
        }

        return keysSet;
    }

    private String tempSplitedStr;       //临时切割得到的字符串

    private final int FLAG_CONVERT_H5TEXT_OVER = 1;  //将H5转换成spanableString 完毕
    private final int MODE_INTRINSIC = 0x001; //根据图片的原始大小进行展示
    private final int MODE_BASE_WINDOW_WITH = 0x002; //与屏幕等宽（保持宽高比）

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != msg && msg.what == FLAG_CONVERT_H5TEXT_OVER) {
                content.setText((SpannableString) msg.obj);
                //设置该句使文本的超连接起作用,不设置该句代码，点击事件不生效！！！
                content.setMovementMethod(LinkMovementMethod.getInstance());
            }
        }
    };


}
